<template>
  <a-row :gutter="10">
    <a-col :md="6" :sm="18">
      <a-card :bordered="false">
        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder="请输入部门名称"/>
          <!-- 树-->
          <template>
            <!--组织机构-->
            <a-tree
              showLine
              :selectedKeys="selectedKeys"
              :checkStrictly="true"
              @select="onSelect"
              :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
              :treeData="departTree"
              :expandedKeys="expandedKeys"
              :defaultExpandParent="autoExpandParent"
              @expand="onExpand"
            />
          </template>
        </div>
      </a-card>
    </a-col>
    <a-col :md="18" :sm="28">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @submit.prevent="searchQuery">
            <a-row :gutter="10">
              <a-col :md="10" :sm="12">
                <a-form-item label="用户账号">
                  <a-input placeholder="请输入用户账号查询" v-model="queryParam.username"></a-input>
                </a-form-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </span>
              </a-col>

            </a-row>
          </a-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="table-operator" :md="24" :sm="24" style="margin-bottom: 10px">
          <a-button @click="handleAdd" type="primary" icon="plus" style="margin-top: 16px">添加</a-button>
        </div>

        <a-table
          ref="table"
          bordered
          rowKey="userId"
          size="middle"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          :scroll="{ x: 1500, y: 300 }"
          :loading="loading"
          @change="handleTableChange">
          <span slot="action" slot-scope="text,record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical"/>

          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="handleDetail(record)">详情</a>
              </a-menu-item>

              <a-menu-item>
                <a href="javascript:;" @click="handleChangePassword(record.username+'@'+record.userId)">密码</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.userId)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="record.lockFlag==0">
                <a-popconfirm title="确定冻结吗?" @confirm="() => handleFrozen(record.id,2,record.username)">
                  <a>冻结</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="record.lockFlag==1">
                <a-popconfirm title="确定解冻吗?" @confirm="() => handleFrozen(record.id,1,record.username)">
                  <a>解冻</a>
                </a-popconfirm>
              </a-menu-item>

            </a-menu>
          </a-dropdown>
        </span>


        </a-table>
        <!-- 表单区域 -->
        <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>
        <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
  import { queryDepartTreeList, deleteDept, updateDept, batchDeleteDept } from '@/api/dept'
  import { queryUserList,deleteUser } from '@/api/user'
  import UserModal from './modules/UserModal'
  import PasswordModal from './modules/PasswordModal'
  import { filterObj } from '@/utils/util';

  export default {
    name: 'User',
    components: {
      UserModal,
      PasswordModal
    },

    data () {
      return {
        currentDeptId: '',
        queryParam: {
          username:''
        },
        expandedKeys: [],
        loading: false,
        autoExpandParent: true,
        currFlowId: '',
        currFlowName: '',
        disable: true,
        treeData: [],
        dataSource: [],
        visible: false,
        departTree: [],
        rightClickSelectedKey: '',
        hiding: true,
        model: {},
        dropTrigger: '',
        depart: {},
        disableSubmit: false,
        checkedKeys: [],
        selectedKeys: [],
        autoIncr: 1,
        pagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        deptId: 0,
        currSelected: {},
        form: this.$form.createForm(this),
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        graphDatasource: {
          nodes: [],
          edges: []
        },
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            align: 'center',
            width: 60,
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '用户账号',
            align: 'center',
            dataIndex: 'username',
            width: 100

          },
          // {
          //   title: '头像',
          //   align: 'center',
          //   width: 120,
          //   dataIndex: 'avatar',
          //   scopedSlots: { customRender: 'avatarslot' }
          // },

          {
            title: '手机号码',
            align: 'center',
            dataIndex: 'phone',
            width: 120
          },
          {
            title: '邮箱',
            align: 'center',
            dataIndex: 'email',
            width: 180
          },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'lockFlag',
            width: 50
          },
          {
            title: '创建时间',
            align: 'center',
            dataIndex: 'createTime',
            sorter: true,
            width: 150
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            align: 'center',
            width: 150
          }

        ]
      }
    },
    created () {
      this.loadTree()
      this.loadUserList()

    },
    methods: {
      callback (key) {
        console.log(key)
      },
      loadData () {
        this.refresh()
      },
      // 加载部门信息
      loadTree () {
        var that = this
        queryDepartTreeList().then((res) => {
          if (res.code == 200) {
            that.departTree = res.data
            // that.treeData = res.data
            for (let i = 0; i < res.data.length; i++) {
              let temp = res.data[i]
              that.setThisExpandedKeys(temp)
            }
            this.loading = false
          }
        })
      },
      getQueryParams() {
        //获取查询条件
        let sqp = {}
        let param = Object.assign(sqp, this.queryParam)
        return filterObj(param);
      },
      // 加载员工信息
      loadUserList () {
        this.loading = true
        const params = new URLSearchParams()
        params.append('current', this.pagination.current)
        params.append('size', this.pagination.pageSize)
        params.append('deptId', this.deptId)
        params.append('username', this.queryParam.username)
        queryUserList(params).then((res) => {
          if (res.code == 200) {
            this.dataSource = res.data.records
            this.pagination.total = res.data.total
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      setThisExpandedKeys (node) {
        if (node.children && node.children.length > 0) {
          this.expandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      refresh () {
        this.loading = true
        this.loadTree()
      },

      onExpand (expandedKeys) {
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },

      onSearch (value) {
        let that = this
        if (value) {
          searchByKeywords({ keyWord: value }).then((res) => {
            if (res.success) {
              that.departTree = []
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                that.departTree.push(temp)
              }
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          that.loadTree()
        }

      },
      onCheck (checkedKeys, e) {
        let record = e.node.dataRef
        // console.log('onCheck', checkedKeys, e);
        this.checkedKeys = []
        // if (e.checked === true) {
        this.currentDeptId = record.id
        this.checkedKeys.push(record.id)

        this.$refs.DeptBaseInfo.open(record)
        this.$refs.DeptUserInfo.open(record)
        // }
        // else {
        //   this.checkedKeys = [];
        //   this.$refs.DeptBaseInfo.clearForm();
        //   this.$refs.DeptUserInfo.clearList();
        // }

        this.hiding = false
        // this.checkedKeys = checkedKeys.checked
      },
      onSelect (selectedKeys, e) {
        if (this.selectedKeys[0] !== selectedKeys[0]) {
          this.selectedKeys = [selectedKeys[0]]
        }
        let record = e.node.dataRef
        this.deptId = record.deptId === 0 ? 0 : record.deptId
        this.currentDeptId = this.deptId;
        this.loadUserList()
      },
      handleTableChange (pagination, filters, sorter) {
        this.pagination = pagination
        this.loadUserList()
      },
      searchQuery () {
        this.loadUserList()
      },
      searchReset () {
        this.queryParam.username = ''
        this.loadUserList()
      },
      handleAdd: function () {
        this.$refs.modalForm.departDisabled = true
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'

      },
      handleEdit: function (record) {
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.departDisabled = true
        this.$refs.modalForm.disableSubmit = false
        this.$refs.modalForm.edit(record)
      },
      handleDelete: function (id) {
        let that = this
        deleteUser(id).then((res) => {
          if (res.code == 200) {
            that.$message.success(res.msg);
            that.loadUserList();
          } else {
            that.$message.warning(res.msg);
          }
        });
      },
      handleDetail:function(record){
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title="详情";
        this.$refs.modalForm.disableSubmit = true;
      },
      handleChangePassword(username) {
        this.$refs.passwordmodal.show(username);
      },
      modalFormOk () {
        // 新增/修改 成功时，重载列表
        this.loadUserList()
      },
      passwordModalOk() {
        //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
      }
    }
  }
</script>
<style scoped>
</style>